
#include "IO.h"
#include "BSP_RS485.h"
#include "BSP_Uart.h"
#include "BSP_Config.h"

#include "Command.h"

const IO_T rs485Dir = IO_INIT_TABLE(RS485_DIR_GP, RS485_DIR_PIN);
static uint32_t rs485Baud;

void BSP_RS485_SetDir(uint8_t dir){
	IO_Set(&rs485Dir, dir);
}

/*---------------------------------------------------------------------------------------------------------*/
/* ISR to handle UART Channel 0 interrupt event                                                            */
/*---------------------------------------------------------------------------------------------------------*/
int Command_Receive(uint8_t channel, unsigned char ch);

static void BSP_RS485_RxIrq(uint8_t rx){
	Command_Receive(CH_UART, rx);
}

void BSP_RS485_Init(void){
	IO_Init(&rs485Dir, IO_Mode_OUT);
	IO_Set(&rs485Dir, RS485_DIR_IN);
	BSP_Uart_Init(RS485_UartId);
	rs485Baud = 115200;
	BSP_Uart_SetBaud(RS485_UartId, 115200);
	BSP_Uart_SetRxCallback(RS485_UartId, BSP_RS485_RxIrq);
}

void BSP_RS485_SetBaud(uint32_t baud){
	if(rs485Baud != baud && baud != 0){
		rs485Baud = baud;
		BSP_Uart_SetBaud(RS485_UartId, baud);
	}
}

void BSP_RS485_RawSend(uint8_t buf[], uint32_t len){
	uint32_t i;
	
	for(i = 0; i < len; i++){
		BSP_Uart_Send(RS485_UartId, buf[i]);
	}
}

void BSP_RS485_RawSendByte(uint8_t ch){
	BSP_Uart_Send(RS485_UartId, ch);
}

void BSP_RS485_SendByte(uint8_t ch){
	BSP_RS485_SetDir(RS485_DIR_OUT);	
	BSP_RS485_RawSendByte(ch);
	BSP_RS485_SetDir(RS485_DIR_IN);
}

void BSP_RS485_SendBuf(uint8_t buf [ ], uint32_t len){
	BSP_RS485_SetDir(RS485_DIR_OUT);	
	BSP_RS485_RawSend(buf, len);
	BSP_RS485_SetDir(RS485_DIR_IN);
}


